﻿using Joy.Erp.BasicArchives.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.DependencyInjection;
using Volo.Abp.EntityFrameworkCore.Modeling;

namespace Joy.Erp.BasicArchives.Sales
{
    public class SaleOrderModelConfiguration : IModelConfiguration
    {
        public void Build(ModelBuilder builder)
        {
            builder.Entity<SaleOrder>(b =>
            {
                b.ToTable(BasicArchivesDbProperties.DbTablePrefix + nameof(SaleOrder), BasicArchivesDbProperties.DbSchema);
                b.ConfigureByConvention();
                b.ConfigureDocumentAggregateRoot<SaleOrder, SaleOrderLine>();

                b.Property(x => x.OrderTypeId).IsRequired(SaleOrderConsts.OrderTypeIdRequired);
                b.Property(x => x.Mark).HasMaxLength(SaleOrderConsts.MarkMaxLength);

                b.HasOne(x => x.OrderType).WithMany().HasForeignKey(x => x.OrderTypeId).OnDelete(DeleteBehavior.Restrict);
                b.HasOne(x => x.Customer).WithMany().HasForeignKey(x => x.CustomerId).OnDelete(DeleteBehavior.Restrict);
                b.HasOne(x => x.Operator).WithMany().HasForeignKey(x => x.OperatorId).OnDelete(DeleteBehavior.Restrict);

                b.HasMany(x => x.Children).WithOne(x => x.Document).HasForeignKey(x => x.DocumentId).OnDelete(DeleteBehavior.Cascade);
            });
        }

        public void Entity(IAbpDbContextRegistrationOptionsBuilder options)
        {
            options.Entity<SaleOrder>(opt =>
            {
                opt.DefaultWithDetailsFunc = query =>
                {
                    return query
                        .Include(x => x.OrderType)
                        .Include(x => x.Customer)
                        .Include(x => x.Operator)
                        .Include(x => x.Children)
                            .ThenInclude(x => x.ItemMaster)
                        .Include(x => x.Children)
                            .ThenInclude(x => x.Unit)
                                .ThenInclude(x => x.Unit)
                        ;
                };
            });
        }
    }
}